package com.li.utilstest

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.annotation.Nullable
import androidx.core.app.NotificationCompat


/**
 * @author : liyun
 * @ClassName: BaseService
 * @Package com.li.utilstest
 * @Description:
 * @company: 深圳君南信息系统有限公司
 * @date 2021/8/22 21:18
 * @version v1.0
 */
abstract class BaseService: Service() {
    val KEEP_SERVICE = 0x11
    open fun BaseService() {}

    override fun onBind(intent: Intent?): IBinder? {
        // TODO: Return the communication channel to the service.
        throw UnsupportedOperationException("Not yet implemented")
    }

    override fun onCreate() {
        super.onCreate()
        createChannel()
        //API 18以下，直接发送Notification并将其置为前台
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            startForeground(KEEP_SERVICE, Notification())
        } else {
            //API 18以上，发送Notification并将其置为前台后，启动InnerService
            var builder: NotificationCompat.Builder? = null
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                builder = NotificationCompat.Builder(this, "Service")
            }
            builder!!.setSmallIcon(R.drawable.ic_launcher)
            startForeground(KEEP_SERVICE, builder.build())
            startService(Intent(this, InnerService::class.java))
            Log.i("Service", "启动InnerService")
        }
        initCreate()
    }

    /**
     * 在设置开启服务通知之前，一定要先创建一个通知渠道，而且两个服务所用的都是同一个渠道
     */
    open fun createChannel() {
        //这里要注意一点：channelid必须要一致，否者服务还是一样会被杀死
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val mNotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val notificationChannel = mNotificationManager.getNotificationChannel("Service")
            if (notificationChannel == null) {
                val channel = NotificationChannel(
                    "Service",
                    "com.li.utilstest", NotificationManager.IMPORTANCE_MIN
                )

                //是否在桌面icon右上角展示小红点
                channel.enableLights(true)

                //小红点颜色
                channel.lightColor = Color.RED

                //通知显示
                channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC

                //是否在久按桌面图标时显示此渠道的通知
                //channel.setShowBadge(true);
                mNotificationManager.createNotificationChannel(channel)
            }
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        initData(intent, flags, startId)
        return START_REDELIVER_INTENT
    }

    abstract fun initData(intent: Intent?, flags: Int, startId: Int)
    abstract fun initCreate()

    inner class InnerService : Service() {
        @Nullable
        override fun onBind(intent: Intent): IBinder? {
            return null
        }

        override fun onCreate() {
            super.onCreate()
            useStartForeground()
            Handler(Looper.getMainLooper()).postDelayed(Runnable {
                stopForeground(true)
                val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    manager.deleteNotificationChannel("Service") //关闭Service前台通知渠道
                }
                stopSelf()
            }, 100)
        }

        fun useStartForeground() {
            val mBuilder = NotificationCompat.Builder(this, "Service")
            mBuilder.setSmallIcon(R.mipmap.ic_launcher)
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                mBuilder.setContentTitle(resources.getString(R.string.name))
            }

            //当id设置为0时，隐藏不显示通知，那么服务在60s后一样时会被杀死的。

            //要如何隐藏通知而服务不被杀死，这个还在学习中。
            startForeground(KEEP_SERVICE, mBuilder.build())
        }
    }
}